#!/usr/bin/env python
# -*- coding: utf8 -*-

import time,os,optparse,cPickle

def diskparam(host):
    try:
        with open('/tmp/monitor-daemon.txt','r') as f:
            alldata = cPickle.load(f)
        result = {}
        temp,res = alldata[host]['check_disk']['info'].split('|')
        for r in res.split(';'):
            p,t,w = r.split(':')
            result[p] = p.replace('X','/')
	return result
    except Exception as err:
        print err
        print '%s get params error,exit run: %s' % (__file__,__file__)

def options():
    usage='''Use like:
%s < -i 192.168.2.10 > < -p check_mem > [ -t 1d ]
''' % __file__
 
    parser = optparse.OptionParser(usage)
    parser.add_option('-i','--ipaddress',dest='hostname',help='Host ipaddress')
    parser.add_option('-p','--project',dest='project',help='the check project')
    parser.add_option('-t','--time',dest='interval',help='the check project')
    return parser

def main():
    parser = options()
    opt,args = parser.parse_args()
    if opt.hostname and opt.project:
        dsindex = []
        otherparam = ''
        colorlist = ['808080','CD853F','00FA9A','0000FF','68228B','8B5A00','96CDCD','CDAD00','CDCDB4','EE8262','EEC900']
        basedir = '/cihi/web/web'
        rrdname = '%s/rrdtool/%s_%s.rrd' % (basedir,opt.hostname,opt.project)
        if opt.interval:
            timelist = [opt.interval]
        else:
            timelist = ['2h','1d','1w','1m','1y']

        if opt.project == 'check_traffic':
            projectdes = '流量'
            axis = '流量（单位：字节）'
            unit = '%10.0lf B/s'
            dsindex = ['tx','rx']
            dslist = {'rx':{'color':'000080','des':'下载','linetype':'LINE1'},'tx':{'color':'00FF00','des':'上传','stack':':STACK','linetype':'AREA'}}
        elif opt.project == 'check_mem':
            projectdes = '内存'
            axis = '内存（单位：字节）'
            unit = '%11.0lf B'
            dsindex = ['use','buffers','cached','free']
            dslist = {'use':{'color':'000080','des':'Use    ','stack':':STACK','linetype':'AREA'},'buffers':{'color':'FFFF00','des':'Buffers','stack':':STACK','linetype':'AREA'},'cached':{'color':'A52A2A','des':'Cached ','stack':':STACK','linetype':'AREA'},'free':{'color':'00FF00','des':'Free   ','stack':':STACK','linetype':'AREA'}}
        elif opt.project == 'check_disk':
            param = diskparam(opt.hostname)
            if param:
                projectdes = '磁盘'
                axis = '磁盘使用率'
                unit = '%5.0lf %%'
                otherparam = '--upper-limit 100'
                dslist = {}
                for part,color in zip(param,colorlist):
                    des = '%-12s' % param[part]
                    dslist[part] = {'color':color,'des':des,'linetype':'LINE1'}
            else:
                parser.error("Missing param,check_disk required partition param")
        elif opt.project == 'check_load':
            projectdes = 'CPU负载'
            axis = '等待CPU处理进程数'
            unit = '%5.2lf'
            otherparam = '-X 0'
            dsindex = ['load1','load5','load15']
            dslist = {'load1':{'color':'000080','des':'最近1分钟 ','linetype':'LINE1'},'load5':{'color':'008000','des':'最近5分钟 ','linetype':'LINE1'},'load15':{'color':'A52A2A','des':'最近15分钟','linetype':'LINE1'}}
        elif opt.project == 'check_procs':
            projectdes = '进程'         
            axis = '总进程数'
            unit = '%10.0lf'
            dslist = {'procs':{'color':'FF4500','des':'进程数  ','linetype':'AREA'}}
        elif opt.project == 'check_ping':
            projectdes = '延迟'
            axis = '延迟（单位：ms）'
            unit = '%5.2lf ms'
            otherparam = '-X 0'
            dslist = {'rta':{'color':'FF4500','des':'延迟','linetype':'LINE1'}}
        elif opt.project == 'check_openfiles':
            projectdes = '打开文件'
            axis = '总打开文件数'
            unit = '%10.0lf'
            otherparam = '-X 0'
            dslist = {'openfiles':{'color':'FF4500','des':'打开文件数','linetype':'LINE1'}}
        elif opt.project == 'check_tcpconnect':
            projectdes = 'TCP连接'
            axis = '总TCP连接数'
            unit = '%10.0lf'
            otherparam = '-X 0'
            dslist = {'tcpconnects':{'color':'FF4500','des':'TCP连接数','linetype':'LINE1'}}


#start image
        for interval in timelist:
            imagename = '%s/static/images/%s_%s_%s.png' % (basedir,opt.hostname,opt.project,interval)
            imgcontrol = ''
            if interval == '2h':
                imgcontrol = "--x-grid MINUTE:5:MINUTE:10:MINUTE:20:0:%H:%M"
                title = '%s--最近2小时%s统计' % (opt.hostname,projectdes)
                interval = '-2h'
            elif interval == '1d':
                imgcontrol = "--x-grid HOUR:1:HOUR:6:HOUR:6:0:%H:%M"
                title = '%s--最近1天%s统计' % (opt.hostname,projectdes)
		interval = '-1d'
            elif interval == '1w':
                title = '%s--最近1周%s统计' % (opt.hostname,projectdes)
		interval = '-1w'
            elif interval == '1m':
                title = '%s--最近1月%s统计' % (opt.hostname,projectdes)
		interval = '-1m'
            elif interval == '1y':
                title = '%s--最近1年%s统计' % (opt.hostname,projectdes)
		interval = '-1y'
            else:
                imagename = '%s/static/images/%s_%s_%s.png' % (basedir,opt.hostname,opt.project,'custom')
                title = '%s--自定义时间统计' % (opt.hostname)
            cmd = '''/usr/bin/rrdtool graph %s -n TITLE:10:'/usr/share/fonts/simhei/simhei.ttf' -n AXIS:10:'/usr/share/fonts/simhei/simhei.ttf' --start %s -t %s -v %s --lower-limit 0 %s %s ''' % (imagename,interval,title,axis,imgcontrol,otherparam)
            if not dsindex:dsindex = dslist
            for type in dsindex:
                cmd += '''DEF:%s_value=%s:%s:AVERAGE:step=60 %s:%s_value#%s:'%s'%s GPRINT:%s_value:LAST:"当前\:%s" GPRINT:%s_value:MAX:"最大\:%s" GPRINT:%s_value:AVERAGE:"平均\:%s" COMMENT:"\\n" ''' % (type,rrdname,type,dslist[type]['linetype'],type,dslist[type]['color'],dslist[type]['des'],dslist[type].get('stack',''),type,unit,type,unit,type,unit)
            cmd += '''COMMENT:"\t\t\t\t\t\t最近一次更新于\:%s"''' % time.strftime('%Y-%m-%d %H:%M:%S').replace(':','\:')
            os.system(cmd)
    else:
        parser.print_help()

if __name__=="__main__":
    main()
